package api.watcher;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

/**
 * 连接状态监视器
 * */
public class KeeperStateWatcher implements Watcher {

    /**
     * KeeperState 通知状态
     * SyncConnected:客户端与服务器正常连接时
     * Disconnected:客户端与服务器断开连接时
     * Expired:会话session失效时
     * AuthFailed:身份认证失败时
     * 事件类型为:None
     * <p>
     * EventType变化时
     * KeeperState永远处于SyncConnected通知状态下；当KeeperState发生变化时，
     * EventType永远为None
     */
    // 连接对象
    static ZooKeeper zooKeeper;


    public void process(WatchedEvent event)  {
        try {
            if (event.getType() == Event.EventType.None) {
                if (event.getState() == Event.KeeperState.SyncConnected) {
                    System.out.println("连接创建成功!");
                } else if (event.getState() == Event.KeeperState.Disconnected) {
                    System.out.println("断开连接！");
                }else if (event.getState() == Event.KeeperState.Expired) {
                    System.out.println("会话超时！");
                    zooKeeper =new ZooKeeper("azyjz.ltd",5000,new KeeperStateWatcher());
                }else if (event.getState() == Event.KeeperState.AuthFailed) {
                    System.out.println("认证失败");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws Exception {
        ZooKeeper zooKeeper = new ZooKeeper("azyjz.ltd", 5000, new KeeperStateWatcher());
        Thread.sleep(1000);

        zooKeeper.addAuthInfo("digest1","yongjianz:12346".getBytes());
        byte [] bs=zooKeeper.getData("/node1",false,null);
        System.out.println(new String(bs));
        Thread.sleep(50000);
        zooKeeper.close();
        System.out.println("结束");
    }
}